package trade.controller;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import trade.bean.TCashierTrade;
import trade.cutil.RestHttpUtil;
import trade.service.ITCashierTradeService;


import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 后台调用 URL
 * http://TradeSys/TradeSys/0.1/indexHtml
 * controller统一处理接收和响应的数据格式
 */
@RestController
@RequestMapping("/TradeSys/${version}")
public class TradeSysController {

    public static final Logger logger = LoggerFactory.getLogger(TradeSysController.class);

    @Autowired
    ITCashierTradeService tradeService;

    @Autowired
    RestTemplate restTemplate;

    @Value("${version}")
    String version;

    //判断系统是否启动欢迎页面页面
    @GetMapping("/indexHtml")
    public String indexHtml() {
        return "TradeSys version " + version + " is running...";
    }

    /**
     *  用户id、订单号、系统名称、和业务名称不能为空
     *  受理时间和初始化状态在接口中定义为当前时间和Created
     * @param msg
     * @return respCode respDesc
     */
    @GetMapping("/insertTrade")
    public String insertTrade(@RequestParam("msg") String msg) {
        logger.info("进入交易系统插入交易信息，接收到数据->" + msg);
        TCashierTrade tCashierTrade = new TCashierTrade();
        try {
            JSONObject jsonObject = new JSONObject(msg);
            tCashierTrade.setUid(jsonObject.getString("uid"));
            tCashierTrade.setOrderId(jsonObject.getString("orderId"));
            tCashierTrade.setSysName(jsonObject.getString("sysName"));
            tCashierTrade.setServ(jsonObject.getString("serv"));
        } catch (Exception e) {
            return reqError("0002");
        }

        tCashierTrade.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        tCashierTrade.setState("Created");
        String response = tradeService.insertTrade(tCashierTrade);
        logger.info("离开交易系统插入交易信息完毕，返回数据->" + response);
        return response;
    }

    /**
     * 更新订单状态和相响应信息或者预留字段
     * 订单号不能为空，状态和返回码描述等可以空
     * @param msg
     * @return respCode respDesc
     */
    @GetMapping("/updateTrade")
    public String updateTrade(@RequestParam("msg") String msg) {
        logger.info("进入交易系统更新交易信息，接收到数据->" + msg);
        TCashierTrade tCashierTrade = new TCashierTrade();
        try{
            JSONObject jsonObject = new JSONObject(msg);
            tCashierTrade.setOrderId(jsonObject.getString("orderId"));
            tCashierTrade.setState(jsonObject.getString("state"));
            if (!jsonObject.isNull("retCode")) {
                tCashierTrade.setRetCode(jsonObject.getString("retCode"));
            }
            if (!jsonObject.isNull("retDesc")) {
                tCashierTrade.setRetDesc(jsonObject.getString("retDesc"));
            }
        } catch (Exception e) {
            return reqError("0002");
        }
        tCashierTrade.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String response = tradeService.updateTrade(tCashierTrade);
        logger.info("离开交易系统更新交易信息完毕，返回数据->" + response);
        return response;
    }

    /**
     * 通过订单号查询交易信息，订单号不能为空
     * @param msg
     * @return JsonObject String of trade
     */
    @GetMapping("/selectTrade")
    public String selectTrade(@RequestParam("msg") String msg) {
        logger.info("进入交易系统查询交易信息，接收到数据->" + msg);
        String response = "";
        try {
            JSONObject jsonObject = new JSONObject(msg);
            response = tradeService.selectTrade(jsonObject.getString("orderId"));
        } catch (Exception e) {
            return reqError("0002");
        }
        logger.info("离开交易系统查询交易信息完毕，返回数据->" + response);
        return response;
    }

    //请求数据异常统一初一方法
    public String reqError(String errorCode) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("respCode",errorCode);
        jsonObject.put("respDesc", RestHttpUtil
                .postHttp(restTemplate ,"http://ErrorSys/ErrorSys/" + version + "/getTradeSysCode/{code}",errorCode));
        return jsonObject.toString();
    }
}
